package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.constant.LoginConstant;
import com.heima.constant.StatusConstant;
import com.heima.exception.BaseException;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.dto.PartnerDto;
import com.heima.pojo.dto.PartnerSearchDto;
import com.heima.pojo.entity.Partner;
import com.heima.pojo.vo.PartnerSearchVO;
import com.heima.pojo.vo.PartnerVO;
import com.heima.service.PartnerService;
import com.heima.utils.Md5Util;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * @author ljk74
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PartnerServiceImpl implements PartnerService {
    private final PartnerMapper partnerMapper;

    @Override
    @Transactional
    public void addPartner(PartnerDto partnerDto) {
        // 判断名称或手机号是否已注册
        Partner isExist = partnerMapper.selectByCondition(partnerDto);
        if (isExist != null) {
            throw new BaseException("名称或手机号已注册");
        }
        //密码加密
        String firstPassword = Md5Util.MD5Lower(partnerDto.getPassword());
        String salt = UUID.randomUUID().toString().replace("-", "");
        String newPassword = salt + Md5Util.MD5Lower(salt + firstPassword);
        // 新增
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDto, partner);
        partner.setStatus(Boolean.valueOf(StatusConstant.ENABLE));
        partner.setPassword(newPassword);
        log.debug("新增结果：{}", partner);
        partnerMapper.insert(partner);
    }

    @Override
    public PartnerSearchVO pageQuery(PartnerSearchDto partnerSearchDto) {
        //检查page相关参数
        partnerSearchDto.check();
        //分页
        PageHelper.startPage(partnerSearchDto.getPageIndex(), partnerSearchDto.getPageSize());
        //查询
        List<PartnerVO> list = partnerMapper.pageQuery(partnerSearchDto);
        Page<PartnerVO> p = (Page<PartnerVO>) list;

        PartnerSearchVO partnerSearchVO = PartnerSearchVO.builder()
                .pageIndex(String.valueOf(partnerSearchDto.getPageIndex()))
                .pageSize(String.valueOf(partnerSearchDto.getPageSize()))
                .totalCount(String.valueOf(p.getTotal()))
                .totalPage(String.valueOf((int) Math.ceil((double) p.getTotal() / partnerSearchDto.getPageSize())))
                .currentPageRecords(p.getResult())
                .build();
        return partnerSearchVO;
    }

    @Override
    public PartnerVO findById(Integer id) {
        log.info("需要查询的id为：{}", id);
        return partnerMapper.findById(id);
    }

    @Override
    public void updatePartner(Integer id, PartnerDto partnerDto) {
        PartnerVO byId = partnerMapper.findById(id);
        if (byId == null) {
            throw new BaseException("该合作商不存在");
        }
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDto, partner);
        partner.setId(id);
        partnerMapper.updateById(partner);
    }

    @Override
    public void delById(Integer id) {
        PartnerVO byId = partnerMapper.findById(id);
        if (byId == null) {
            throw new BaseException("该合作商不存在");
        }
        if (byId.getVmCount() > 0) {
            throw new BaseException("该合作商关联着设备，不能删除");
        }
        partnerMapper.deleteById(id);
    }

    @Override
    public void resetPwd(Integer id) {
        PartnerVO byId = partnerMapper.findById(id);
        if (byId == null) {
            throw new BaseException("该合作商不存在");
        }
        //默认密码
        String firstPassword = Md5Util.MD5Lower(LoginConstant.DEFAULT_PWD);
        String salt = UUID.randomUUID().toString().replace("-", "");
        String newPassword = salt + Md5Util.MD5Lower(salt + firstPassword);

        Partner partner = Partner.builder()
                .id(id)
                .password(newPassword)
                .build();
        partnerMapper.updateById(partner);
    }
}
